# 设置最低CMake版本要求
cmake_minimum_required(VERSION 3.10)

# 设置项目名称和版本
project(MathLibrary VERSION 1.0)

# 设置C标准
set(CMAKE_C_STANDARD 17)
set(CMAKE_C_STANDARD_REQUIRED ON)

# 添加编译选项
if(MSVC)
    add_compile_options(/W4)
else()
    add_compile_options(-Wall -Wextra -fPIC)
endif()

# 创建静态库
add_library(math_static STATIC
    xjiami/mathlib.c
)

# 创建动态库
add_library(math_shared SHARED
    xjiami/mathlib.c
)

# 设置库的输出名称
set_target_properties(math_static PROPERTIES OUTPUT_NAME math)
set_target_properties(math_shared PROPERTIES OUTPUT_NAME math)

# 在Windows上为动态库设置正确的前缀和后缀
if(WIN32)
    set_target_properties(math_shared PROPERTIES
        PREFIX ""
        SUFFIX ".dll"
    )
endif()

# 设置库的版本属性
set_target_properties(math_shared PROPERTIES
    VERSION ${PROJECT_VERSION}
    SOVERSION ${PROJECT_VERSION_MAJOR}
)

# 创建使用静态库的测试程序
add_executable(test_static test.c)
target_link_libraries(test_static math_static)

# 创建使用动态库的测试程序
add_executable(test_shared test.c)
target_link_libraries(test_shared math_shared)

# 设置头文件包含目录
target_include_directories(math_static PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_include_directories(math_shared PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

# 安装规则
include(GNUInstallDirs)

# 安装库文件
install(TARGETS math_static math_shared
    ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)

# 安装头文件
install(FILES mathlib.h
    DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)

# 安装可执行文件
install(TARGETS test_static test_shared
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)

# 为动态库设置RPATH
if(UNIX)
    set_target_properties(test_shared PROPERTIES
        INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}"
        BUILD_WITH_INSTALL_RPATH TRUE
    )
endif()